import java.util.concurrent.Semaphore;

public class ThreadDemo22 {
    public static void main(String[] args) {
        Semaphore semaphore=new Semaphore(4);//4个可用资源

        Runnable runnable=new Runnable() {
            @Override
            public void run() {

                try {
                    System.out.println("准备申请资源");
                    //申请资源
                    semaphore.acquire();//信号量的P操作，申请资源
                    System.out.println("申请资源成功");
                    //申请到之后，sleep 1s
                    Thread.sleep(1000);
                    //再释放资源
                    semaphore.release();//信号量的V操作，释放资源
                    System.out.println("完成释放资源");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        };


        //创建20个线程，让它们分别去尝试申请资源
        for (int i = 0; i <20; i++) {
            Thread t=new Thread(runnable);
            t.start();
        }
    }
}
